package com.iceking.dao;

import com.iceking.model.Article;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.util.List;

/**
 * Created by I on 2015/9/23.
 */
@Repository
public class ArticleDaoImplHiber implements ArticleDao {

    @Autowired
    private SessionFactory sessionFactory;

    @Transactional
    public void add(Article article) {
        Session session = sessionFactory.getCurrentSession();
        session.save(article);
    }

    @Transactional
    public void update(Article article) {
        Session session = sessionFactory.getCurrentSession();
        session.update(article);
    }

    @Transactional
    public void delete(long id) {
        Session session = sessionFactory.getCurrentSession();
        Article article = (Article) session.load(Article.class, id);
        session.delete(article);
    }

    @Transactional
    public List<Article> getAll() {
        Session session = sessionFactory.getCurrentSession();
        List<Article> list = session.createQuery("from Article").list();
        return list;
    }

    @Transactional
    public Article getArticleById(long id) {
        Session session = sessionFactory.getCurrentSession();
        Article article = (Article) session.load(Article.class, id);
        return article;
    }
}
